/**
 * @description 扣费校验规则  暂时不用，废弃
 */
import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'

import { FeeDeductionRuleTypeCnEnum, getKeyToEnum, ValidRuleTypeCnEnum } from '@/const/enum'
import type { OptionDto } from '@/components/low-code/types'
import { numberToLetter } from '@/utils/util'
import { Button, Input, Select, Timeline, TimelineItem, TimePicker } from 'ant-design-vue'
import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'

export interface FeeDeductionRuleDto {
    type: number
    list: ValidRuleItemDto[]
}

export interface ValidRuleDto {
    type: number
    date: string
    monthType: number
    day: number | null
    fee: number | null
}

export interface FeeDecutionRuleItemDto extends FeeDeductionRuleDto {
    options?: OptionDto[]
}

export interface ValidRuleItemDto extends ValidRuleDto {
    options?: OptionDto[]
}

@Component
export class FeeDeductionRule extends Render {
    ruleList = [] as FeeDecutionRuleItemDto[]

    options = getKeyToEnum(FeeDeductionRuleTypeCnEnum)

    validOptions = getKeyToEnum(ValidRuleTypeCnEnum)

    @Emit('update:modelValue')
    handleEmitUpdate(val: FeeDeductionRuleDto[]) {
        return val
    }

    @Watch('modelValue', { deep: true, immediate: true })
    handleWatchValiateRuleData(val: FeeDeductionRuleDto[]) {
        this.ruleList = val || []
        // 没有值时默认添加一条
        if (!this.ruleList.length) {
            this.ruleList.push(this.createRuleData())
            this.handleEmitUpdate(this.ruleList)
        }
    }

    // 创建规则，过滤生效方式及其默认值
    createRuleData() {
        const typesValue = this.ruleList.map((i) => i.type)
        const options = this.options.filter((i) => !typesValue.includes(i.value as number))
        const defaultType = options[0].value as number
        const defaultValue = {
            type: defaultType,
            options: options,
            list: [] as ValidRuleItemDto[]
        }
        defaultValue.list.push(this.createValidRule(0))
        return defaultValue
    }

    // 创建灵活方案下的规则
    createValidRule(parentIndex: number) {

        const typesValue = this.ruleList[parentIndex].list.map((i) => i.type)
        const options = this.validOptions.filter((i) => !typesValue.includes(i.value as number))
        const defaultType = options[0].value as number
        return {
            type: defaultType,
            date: '',
            options: options,
            monthType: 1,
            day: null,
            fee: null
        }
    }

    // 添加扣费规则
    onAddRule() {
        const rule = this.createRuleData()
        this.ruleList.push(rule)
        this.handleRefreshOption(rule, 'add')
    }

    // 添加灵活方案下的生效方式
    onAddValidRule(parentIndex: number) {
        const rule = this.createValidRule(parentIndex)
        this.ruleList[parentIndex].list.push(rule)
        this.handleRefreshOption(rule, 'add', parentIndex)
    }

    // 删除扣费规则
    onRemove(ruleData: FeeDecutionRuleItemDto, index: number) {
        this.ruleList.splice(index, 1)
        this.handleRefreshOption(ruleData, 'remove')
    }

    // 删除灵活方案下的生效方式
    onRemoveValidRule(ruleData: ValidRuleItemDto, parentIndex: number, index: number) {
        this.ruleList[parentIndex].list.splice(index, 1)
        this.handleRefreshOption(ruleData, 'remove', parentIndex)
    }

    // 新增或删除时，刷新其他规则的生效方式的options
    handleRefreshOption(curRule: FeeDecutionRuleItemDto | ValidRuleItemDto, type: string, index?: number) {
        const list = index === undefined ? this.ruleList : this.ruleList[index]?.list
        switch (type) {
        case 'add':
            // 新增时要在已存在的规则中把新生成的一条的生效方式从options中移除
            list.forEach((item, idx) => {
                if (idx !== list.length - 1) {
                    const index = item.options?.findIndex((i) => i.value === curRule?.type)
                    if (index !== -1) {
                        item.options?.splice(index as number, 1)
                    }
                }
            })
            break
        case 'remove':
            // 移除时要在已存在的规则中把删除的生效方式从options中加回去
            list.forEach((item) => {
                item.options?.push(...(curRule.options as OptionDto[]))
            })
        }
    }

    // 外层的方案类型
    renderRule(ruleData: FeeDecutionRuleItemDto, index: number) {
        return (
            <div class="leading-10">
                <div class="flex items-center">
                    <div>
                        <span>方案类型等于</span>
                        <Select v-model={ruleData.type} options={ruleData?.options} class="!w-120px px-5px">
                            {/* {ruleData?.options?.map((item) => (
                                <ElOption
                                    label={item.label}
                                    value={item.value as number}
                                ></ElOption>
                            ))} */}
                        </Select>
                        <span>时；</span>
                        {this.renderRuleDetail(ruleData, index)}
                    </div>
                    <div>
                        {this.ruleList.length !== 1 && (
                            <div
                                class="cursor-pointer"
                                onClick={() => this.onRemove(ruleData, index)}
                            >
                                <CloseOutlined />
                            </div>
                        )}
                    </div>
                </div>
            </div>
        )
    }

    renderFlexableRule(ruleData: ValidRuleItemDto, index: number) {
        switch (ruleData.type) {
        case ValidRuleTypeCnEnum.次日生效:
            return (
                <>
                    <span>生效方式等于</span>
                    <Select class="!w-110px px-5px" v-model={ruleData.type} options={ruleData?.options}>
                    </Select>
                    <span>时，按天立即扣费。第一次激活时和次日生效的方案扣费时间一致。</span>
                </>
            )
        case ValidRuleTypeCnEnum.整点生效:
            return (
                <>
                    <span>生效方式等于</span>
                    <Select class="!w-110px px-5px" v-model:value={ruleData.type} options={ruleData?.options}>
                    </Select>
                    <span>时；生效前一天</span>
                    <TimePicker
                        v-model={ruleData.date}
                        class="!w-100px px-5px"
                    ></TimePicker>
                    <span>扣除次日保费。</span>
                </>
            )
        }
    }

    renderMonthRule(ruleData: ValidRuleItemDto, index: number) {
        console.log(321312, ruleData.type)
        switch (ruleData.type) {
        case FeeDeductionRuleTypeCnEnum.月单:
            return (
                <div class="flex flex-wrap leading-10">
                    <span>生效方式等与</span>
                    <Select class="!w-110px px-5px" v-model:value={ruleData.type} disabled options={getKeyToEnum(FeeDeductionRuleTypeCnEnum, false, ['月单'])}>
                    </Select>
                    <span>时；生效前一天</span>
                    <TimePicker
                        v-model={ruleData.date}
                        class="!w-100px px-5px"
                    ></TimePicker>
                    <span>扣除保费。</span>
                    <Select class="!w-110px px-5px" v-model={ruleData.monthType} disabled>
                    </Select>
                    <Input v-model:value={ruleData.day} class="!w-100px px-5px"></Input>
                    <span>日之后生效，扣除</span>
                    <Input v-model:value={ruleData.fee} class="!w-100px px-5px"></Input>
                    <span>倍月保费。</span>
                </div>
            )
        }
    }

    // 内层的生效类型
    renderRuleDetail(ruleData: FeeDecutionRuleItemDto, idx: number) {
        switch (ruleData.type) {
        case FeeDeductionRuleTypeCnEnum.灵活方案:
            return (
                <div class="mt-10px leading-10">
                    <Timeline>
                        {ruleData.list.map((i, index) => {
                            return (
                                <TimelineItem
                                    v-slots={{
                                        dot: () => {
                                            return (
                                                <div class="text-blue-default font-bold after:content-['或'] after:block">
                                                    {numberToLetter(index + 1)}
                                                    {index + 1}
                                                </div>
                                            )
                                        },
                                        default: () => {
                                            return (
                                                <div class="flex flex-wrap">
                                                    {this.renderFlexableRule(i, index)}

                                                    {ruleData.list.length !== 1 && (
                                                        <div>
                                                            <div
                                                                class="cursor-pointer mt-5px"
                                                                onClick={() =>
                                                                    this.onRemoveValidRule(
                                                                        i,
                                                                        idx,
                                                                        index
                                                                    )
                                                                }
                                                            >
                                                                <CloseOutlined />
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            )
                                        }
                                    }}
                                ></TimelineItem>
                            )
                        })}
                        {ruleData.list.length !== this.options.length && (
                            <TimelineItem
                                v-slots={{
                                    dot: () => {
                                        return <div class="text-blue-default font-bold">B1</div>
                                    },
                                    default: () => {
                                        return (
                                            <Button
                                                icon={h(PlusOutlined)}
                                                onClick={() => this.onAddValidRule(idx)}
                                            >
                                                    添加条件
                                            </Button>
                                        )
                                    }
                                }}
                            ></TimelineItem>
                        )}
                    </Timeline>
                </div>
            )
        case FeeDeductionRuleTypeCnEnum.月单:
            return (
                <div class="mt-10px">
                    <Timeline>
                        {ruleData.list.map((i, index) => {
                            return (
                                <TimelineItem
                                    v-slots={{
                                        dot: () => {
                                            return (
                                                <div class="text-blue-default font-bold after:content-['或'] after:block">
                                                    {numberToLetter(index + 1)}
                                                </div>
                                            )
                                        },
                                        default: () => {
                                            return (
                                                <div class="flex">
                                                    {this.renderMonthRule(i, index)}
                                                </div>
                                            )
                                        }
                                    }}
                                ></TimelineItem>
                            )
                        })}
                    </Timeline>
                </div>
            )
        }
    }

    render() {
        return (
            <>
                <Timeline>
                    {this.ruleList.map((i, index) => {
                        return (
                            <TimelineItem
                                v-slots={{
                                    dot: () => {
                                        return (
                                            <div class="text-blue-default font-bold after:content-['或'] after:block">
                                                A
                                            </div>
                                        )
                                    },
                                    default: () => {
                                        return <div class="flex">{this.renderRule(i, index)}</div>
                                    }
                                }}
                            ></TimelineItem>
                        )
                    })}
                    {this.ruleList.length !== this.options.length && (
                        <TimelineItem
                            v-slots={{
                                dot: () => {
                                    return <div class="text-blue-default font-bold">B</div>
                                },
                                default: () => {
                                    return (
                                        <Button icon={h(PlusOutlined)} onClick={this.onAddRule}>
                                            添加条件
                                        </Button>
                                    )
                                }
                            }}
                        ></TimelineItem>
                    )}
                </Timeline>
            </>
        )
    }
}

export default toNative<{}, {}>(FeeDeductionRule)
